//
//  UserAccountViewModel.swift
//  JKDWeiBoExercise
//
//  Created by 简康达 on 16/5/21.
//  Copyright © 2016年 JKD. All rights reserved.
//

import UIKit

class UserAccountViewModel{
    static let shareIntance : UserAccountViewModel = UserAccountViewModel()
    var account :UserAccount?
    var isLogin : Bool {
    return account != nil && !isExpires
    }
    var isExpires : Bool {
        guard let expire_date = account?.expires_date else {
            return true
        }
        return expire_date.compare(NSDate()) == NSComparisonResult.OrderedAscending
    }
    var accountPath : String {
        let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first!
        return (path as NSString).stringByAppendingPathComponent("accout.plist")
    }
    init() {
        account = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? UserAccount
    }
    
}
// MARK:- 获取accessToken
extension UserAccountViewModel {
     func loadAccessToken(codeString:String){
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let parameters = ["client_id":app_key,"client_secret":app_secret,"grant_type":"authorization_code","code":codeString,"redirect_uri":redirect_uri]
        
        NetworkTools.shareIntance.loadDataThroughInternet(urlString: urlString, parameters:parameters) { (result, error) in
            if error != nil {
                print(error)
                return
            }
            guard let account : UserAccount = UserAccount(dict: result as! [String:AnyObject]) else{
                return
            }
            //            获取用户信息
            self.loadUserInfo(account)
            
        }
    }
}
//MARK:- 获取用户信息
extension UserAccountViewModel{
    private func loadUserInfo(account : UserAccount){
        let urlString = "https://api.weibo.com/2/users/show.json"
        let parameters = ["access_token":account.access_token!,"uid":account.uid!]
        NetworkTools.shareIntance.loadDataThroughInternet(.GET, urlString: urlString, parameters:parameters) { (result, error) in
            if error != nil {
                print(error)
                return
            }
            guard let userInfoDict = result as? [String:AnyObject] else{
                return
            }
            account.screen_name = userInfoDict["screen_name"] as? String
            account.avatar_large = userInfoDict["avatar_large"] as? String
            print(account)
            //            将用户信息保存到沙盒
//            var path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first
//            path = (path! as NSString).stringByAppendingPathComponent("accout.plist")
            NSKeyedArchiver.archiveRootObject(account, toFile:self.accountPath)
            self.account = account
            UIApplication.sharedApplication().keyWindow?.rootViewController = WelComeViewController()
        }
    }
}